import React, { useEffect, useReducer, useState } from 'react'
import 'react-native-gesture-handler'
import Routes from './src/routes'
import * as front from 'expo-font'
import * as SplashScreen from 'expo-splash-screen'
import useUserCartContext, {
  userCartContext,
  cartReducer,
} from './src/context/userCartContext'
import { cartData } from './src/assets/data/data'
import { observer } from 'mobx-react-lite'
import AsyncStorage from '@react-native-async-storage/async-storage'
import { useStore } from './src/store'

export default observer(function App(): JSX.Element {
  const [data, dispatch] = useReducer(cartReducer, [])
  return (
    <userCartContext.Provider value={{ data, dispatch }}>
      <AppWrap />
    </userCartContext.Provider>
  )
})
function AppWrap() {
  const finished = useInit()
  if (!finished) {
    return null
  }
  return <Routes />
}
function useInit() {
  const { userStore } = useStore()
  const [checkUser, setCheckUser] = useState(false) // 检查用户信息是否检查完毕
  const [finished, setFinished] = useState(false)
  const [fontsLoaded] = front.useFonts({
    // 加载字体
    iconfont: require('./src/assets/fonts/iconfont.ttf'),
  })
  AsyncStorage.getItem('userInfo').then(res => {
    // 加载用户信息
    res && userStore.SET_USER_INFO(JSON.parse(res))
    setCheckUser(true)
  })
  const { dispatch } = useUserCartContext()
  useEffect(() => {
    dispatch({
      type: 'init',
      initData: cartData.map(item => Object.assign({ choosed: false }, item)),
    })
  }, [])
  useEffect(() => {
    if (fontsLoaded && checkUser) {
      SplashScreen.hideAsync()
      setFinished(true)
    }
  }, [fontsLoaded, checkUser])

  return finished
}
